<template>
  <div>
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline" v-hasPermi="['md:school:product:query']">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model.trim="queryParams.projectName" :maxlength="25" size="small" placeholder="请输入项目名称"></el-input>
      </el-form-item>
      <el-form-item label="项目编号" prop="projectNo">
        <el-input v-model.trim="queryParams.projectNo" :maxlength="25" size="small" placeholder="请输入项目编号"></el-input>
      </el-form-item>
      <el-form-item label="产品名称" prop="deviceName">
        <el-input v-model.trim="queryParams.deviceName" :maxlength="25" size="small" placeholder="请输入产品名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['md:school:product:query']" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" v-hasPermi="['md:school:product:query']" @click="resetForm('queryFormRef')">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="20"> -->
      <!-- <el-col :span="6">
        <div class="grid-content bg-purple text">
          <span>本页总金额(万元)：{{ currentAmount }}</span>
        </div>
      </el-col> -->
      <!-- <el-col :span="24"> -->
        <div class="grid-content bg-purple text">
          <span>总价(元)：{{ allAmount }}</span>
        </div>
      <!-- </el-col>
    </el-row> -->

    <el-table
      :data="tableData"
      v-loading="loading"
      highlight-current-row
      max-height="300"
      v-horizontal-scroll="'auto'"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="projectName"
        label="项目名称"
        align="center"
      />
      <el-table-column
        property="projectNo"
        label="项目编号"
        align="center"
      />
      <el-table-column
        property="name"
        label="产品名称"
        align="center"
      />
      <el-table-column
        property="deviceNo"
        label="型号"
        align="center"
      />
      <el-table-column
        property="type"
        label="类型"
        align="center"
      />
      <el-table-column
        property="product"
        label="标准产品"
        align="center"
      />
      <el-table-column
        property="num"
        label="数量"
        align="center"
      />
      <el-table-column
        property="amount"
        label="单价(元)"
        align="center"
      />
      <el-table-column
        property="totalAmount"
        label="总价(元)"
        align="center"
      />
      <el-table-column
        property="deliveryDate"
        label="交付日期"
        align="center"
      />
      <el-table-column
        property="guaranteeDate"
        label="质保日期"
        align="center"
      />
      <el-table-column
        property="contactName"
        label="联系人"
        align="center"
      />
      <el-table-column
        property="contactPhone"
        label="联系人电话"
        align="center"
      />
      <el-table-column
        property="agentName"
        label="代理商"
        align="center"
        v-if="schoolInfo.queryType === 0"
      />
      <el-table-column
        property="clientName"
        label="所属客户"
        align="center"
        v-if="schoolInfo.queryType === 1"
      />
      <el-table-column
        property="facultyName"
        label="所属院系"
        align="center"
        v-if="schoolInfo.queryType === 1"
      />
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :autoScroll="false"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '增加' : '修改'"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form">
        <el-form-item label="学校名称" prop="schoolName">
          <el-input v-model.trim="schoolInfo.clientName" disabled placeholder="请输入学校名称"></el-input>
        </el-form-item>
        <el-form-item label="二级部门名称" prop="faculty">
          <el-input v-model.trim="schoolInfo.name" disabled placeholder="请输入二级部门名称"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="deviceName">
          <el-input v-model.trim="form.deviceName" :maxlength="25" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number v-model="form.num" :min="1" label="请输入数量"></el-input-number>
        </el-form-item>
        <el-form-item label="总金额" prop="amount">
          <el-input v-model.trim="form.amount" :min="0" type="number" placeholder="请输入金额"
            @input="inputHandler"
          >
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/md/school/product";
// import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
// import { number } from "echarts";

export default {
  name: 'SchoolProduct',
  // dicts: ['sys_key_customer_basis'],
  props: ['schoolInfo'],
  data() {
    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      currentAmount: 0, // 当前预算金额
      allAmount: 0, // 总预算金额
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        amount: "", // 金额
        companyName: "", // 公司名称 实验室现状
        createBy: "", // 创建人
        createTime: "", // 创建时间
        deviceName: "", // 设备名称
        faculty: "", // 二级部门名称
        facultyId: null, // 二级部门id
        id: null, // id
        num: 1, // 产品数量
        remark: "", // 备注
        schoolName: "", // 学校名称 已购产品
        type: 0, // 类型 0是已购产品 1是实验室现状
        updateBy: "", // 更信人
        updateTime: "", // 更新时间
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        deviceName: [
          { required: true, message: '请填写设备名称', trigger: 'blur' }
        ],
        // isImportant: [
        //   { required: true, message: '请选择客户属性', trigger: 'change' }
        // ],
        num: [
          { required: true, message: '请填写数量', trigger: 'blur' }
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        projectName: null,
        projectNo: null,
        facultyId: null, // 二级部门id
        deviceName: "", // 设备名称
        // type: 0, // 类型 0是已购产品 1是实验室现状
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
    }
  },
  watch: {
    'form.isImportant': {
      handler(newV) {
        if(newV !== 1) {
          this.form.basis = null
        }
      }
    },
    schoolInfo: {
      deep: true,
      immediate: true,
      handler(newV) {
        if(newV.queryType) {
          this.queryParams.agentId = newV.id
        } else {
          this.queryParams.facultyId = newV.id
        }
        this.searchHandler()
      },
    },
  },
  created() {
    // this.provinceList = ProvinceData
    // this.getList()
    this.getUserinfo()
  },
  methods: {
    // 用户输入的回调
    inputHandler(e) {
      if(+e < 0) this.form.amount = 0
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if(+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if(res.code === 200) {
        this.tableData = res.data?.list?.rows ?? []
        this.total = res.data?.list?.total ?? 0

        this.allAmount = res.data?.amount ?? 0

        this.currentAmount = this.tableData.reduce((acc, cur) => acc + (cur.amount ?? 0), 0)
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = { ...row }
        this.dialogTitle = 2
      } else {
        if(this.formId) {
          this.form = { ...this.$options.data().form }
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(()=>{
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/buyOrLaboratory/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `buyProducts_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      // if(this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
        facultyId: this.schoolInfo.id,
        type: 0,
      }
      const res = await addDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
        facultyId: this.schoolInfo.id,
        type: 0,
      }
      const res = await updateDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    }
  },
}
</script>
<style scoped lang="scss">
.grid-content.text{
  margin-top: 10px;
  color: red;
}
</style>
